import 'dart:async';
import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:http/http.dart' as http;

const String apiUrl =
    // 'http://api.fanyi.baidu.com/api/trans/vip/translate'; // 百度翻译API地址
    'https://fanyi-api.baidu.com/api/trans/vip/translate'; // 百度翻译API地址
const String appId = '20240806002117441';
const String appSecret = 'Fkwapyw5iRjZP1_c6UDm';

Future<List<dynamic>> baiduTranslate({
  required String query,
  required String to,
}) async {
  String queryStr = query;
  int salt = DateTime.now().millisecondsSinceEpoch;
  String from = 'zh';
  String str = '$appId$queryStr$salt$appSecret';
  String sign = md5.convert(utf8.encode(str)).toString();

  Map<String, String> details = {
    'appid': appId,
    'salt': '$salt',
    'from': from,
    'to': to,
    'sign': sign,
    'q': queryStr,
  };

  Uri uri = Uri.parse(apiUrl);
  Map<String, String> body = details;

  try {
    final resp = await http.post(
      uri,
      body: body,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      },
    );

    if (resp.statusCode == 200) {
      var result = jsonDecode(resp.body);
      if (result['trans_result'] != null) {
        return result['trans_result'];
      } else {
        print('调取百度翻译错误:' + result['error_msg']);
        return [];
      }
    } else {
      print(resp.statusCode);
      print(resp.body);
      return [];
    }
  } catch (error) {
    print('translate error: $error');
    return [];
  }
}

// 使用示例
void main() async {
  // 测试 百度翻译
  try {
    final result = await baiduTranslate(query: "今天吃饭了吗?", to: "hu");
    // final result = await baiduTranslate(query: "今天吃饭了吗？", to: "jp");
    print(result);
  } catch (e) {
    print(e);
  }
}
